package com.tenclass.common.interceptor;

import com.tenclass.common.annotation.AdminApi;
import com.tenclass.common.annotation.InnerApi;
import com.tenclass.common.annotation.NoAuth;
import com.tenclass.common.interceptor.request.AdminInterceptor;
import com.tenclass.common.interceptor.request.InnerInterceptor;
import com.tenclass.common.interceptor.request.UserInterceptor;
import com.tenclass.common.model.CurrentUser;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import static com.tenclass.common.constant.RequestConstant.CURRENT_USER;

/**
 * 请求方法拦截器
 *
 * @author YIJIUE
 * @since 1.0.0
 */
public class RequestInterceptor implements HandlerInterceptor {

    /**
     * 此处无需过多设计，如不适合所用场景 可自定义一个 拦截器
     * 参考 {@link com.tenclass.common.configuration.WebConfiguration} 添加拦截器方法
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理对象
     * @return true or false
     */
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        // 是否调用方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (isHave((HandlerMethod) handler, NoAuth.class)) {
            // 有些场景 noauth的情况下 某些接口需要带 用户信息
            String user = request.getHeader(CURRENT_USER);
            if (!StringUtils.isEmpty(user)) {
                CurrentUser.set(URLDecoder.decode(user, StandardCharsets.UTF_8));
            }
            return true;
        }

        if (isHave((HandlerMethod) handler, InnerApi.class)) {
            return new InnerInterceptor().preHandle(request);
        } else if (isHave((HandlerMethod) handler, AdminApi.class)) {
            return new AdminInterceptor().preHandle(request);
        } else {
            return new UserInterceptor().preHandle(request);
        }
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        // 无论是否用经过 user 拦截器 都安全清除下
        CurrentUser.clear();
    }

    public boolean isHave(HandlerMethod handler, Class<? extends Annotation> annotation) {
        return handler.getMethodAnnotation(annotation) != null || (handler.getBean().getClass().getAnnotation(annotation) != null);
    }

}
